const db = require('../model/db')
const Base = require('./base')

const TableName = 'tk_article'

class Article extends Base {
  // 列表
  async findAll(req, res) {
    const { title, page = 1, limit = 10, modelid, catid, colPid } = req.query
    const startIndex = (page - 1) * limit
    const app_id = req.headers.appid || 1
    const data = { total: 0, rows: [] }
    const modelId = Number(modelid) ? `= ${modelid}` : 'is not null'
    const catId = catid ? ` and tk_article.catid = ${catid}` : ''
    const pid = colPid ? ` and tk_article.colPid = ${colPid}` : ''

    const sql1 = `
      select tk_article.*, tk_category.colTitle as category_title, tk_category.description as category_description, tk_category.model as model, tk_category.modelid as modelid
      from tk_article
      inner join tk_category
      on tk_article.catid = tk_category.id
      where tk_article.app_id = ${app_id} and tk_category.modelid ${modelId} ${catId} ${pid} and tk_article.title LIKE ? order by tk_article.id desc LIMIT ?, ?
    `
    const sql2 = `select count(*) as total from ${TableName} where title LIKE ? and app_id = ${app_id} and modelid ${modelId} ${catId}`

    const [rows] = await db.query(sql1, [`%${title || ''}%`, startIndex, Number(limit)])
    const [[{ total }]] = await db.query(sql2, [`%${title || ''}%`])

    if (rows.length > 0) {
      data.rows = rows
      data.total = total
    }

    return res.cc('success', 0, { data })
  }

  // 详情
  async findOne(req, res) {
    const { id } = req.params
    const data = { total: 0, rows: { comments: [] } }
    const sql = `select * from ${TableName} where id = ?`
    const sql2 = 'select * from tk_comment where bid = ? order by id desc'

    const [[rows]] = await db.query(sql, [id])
    const [rows2] = await db.query(sql2, [id])

    if (rows) {
      const { views } = rows

      this.updateFileds({ id, fileds: { views: Number(views) + 1 } })

      data.rows = rows
      data.rows.comments = rows2
    }

    return res.cc('success', 0, { data })
  }

  // 修改字段
  async updateFileds({ id, fileds, res }) {
    const sql = `update ${TableName} set ? where id=?`

    const [rows] = await db.query(sql, [fileds, id])

    return rows.affectedRows
  }

  async create(req, res) {
    await this.baseCreate(req, res)
  }

  async update(req, res) {
    await this.baseUpdate(req, res)
  }

  async remove(req, res) {
    await this.baseRemove(req, res)
  }

  async like(req, res) {
    const { id, likes } = req.body
    const sql = `select * from ${TableName} where id = ?`
    const [[rows]] = await db.query(sql, [id])
    const data = { likes: 0 }

    if (!likes) {
      return res.cc('likes参数不能为空')
    }

    if (Number(likes) > rows.likes + 10) {
      return res.cc('点的太快了')
    }

    if (rows) {
      data.likes = likes
      const result = this.updateFileds({ id, fileds: { likes } })

      if (result) {
        return res.cc('success', 0, { data })
      }
    }
  }
}

module.exports = Article
